import { KanbanService } from './../../@core/mock/kanbanSerive/kanban.service';
import { WorkbenchService } from './../../@core/mock/datasERVICE/workbench.service';
import { animate, style, transition, trigger } from '@angular/animations';
import { HttpClient } from '@angular/common/http';
import { ChangeDetectorRef, Component, ElementRef, ViewChild } from '@angular/core';
import * as echarts from 'echarts';

@Component({
  selector: 'app-shengchan-kanban',
  templateUrl: './shengchan-kanban.component.html',
  styleUrls: ['./shengchan-kanban.component.scss'],

})
export class ShengchanKanbanComponent {
  zantingData: any = [
    {
        "pauseReason": "设备故障",
        "count": 335
    },
    {
        "pauseReason": "中途离开",
        "count": 310
    },
    {
        "pauseReason": "原料不足",
        "count": 234
    },
    {
        "pauseReason": "人为原因",
        "count": 135
    },
    {
        "pauseReason": "其他原因",
        "count": 1548
    }
  ]
  constructor(private cdr: ChangeDetectorRef, private http: HttpClient, private KanbanService: KanbanService) { }
  intervalId: any;
  jobOrderData: any = {
    "jobOrderProcessCount": 0,
    "todayJobOrderProcessCompletedCount": 0,
    "weekJobOrderProcessCompletedCount": 0,
    "monthJobOrderProcessCompletedCount": 0,
    "jobOrderProcessCompletedCount": 0,
    "jobOrderCount": 0,
    "jobOrderCompletedCount": 0,
    "plannedProductionCount": 0,
    "producedCount": 0
  }
  messages:any = [];
  processStatusData: any = {
    "jobOrderProcessStartedCount": 0,
    "jobOrderProcessNotStartedCount": 0,
    "jobOrderProcessPausedCount": 0,
    "jobOrderProcessCompletedCount": 0
  }
  reportingQualifiedRate:any = {
    "totalReportedCount": 0,
    "totalQualifiedCount": 0,
    "totalUnqualifiedCount": 0,
    "totalScrapCount": 0
  }
  ngOnInit(): void {
    this.KanbanService.getJobOrderKanbanData().subscribe((res) => {
      this.jobOrderData = res;
    })
    this.KanbanService.getJobOrderProcessCount().subscribe((res) => {
      this.processStatusData = res;
      this.initChart();
    })
    this.KanbanService.getReportingQualifiedRate().subscribe((res) => {
      this.reportingQualifiedRate = res;
      this.initChart2();
    })
    this.KanbanService.getJobOrderProcessYearCount().subscribe((res) => {
      this.initBarChart(res)
    })
    this.KanbanService.getCompletedQuantityWeek().subscribe((res) => {
      this.initLineChart(res)

    })
    this.KanbanService.getPausedReason().subscribe((res) => {
      this.zantingData = this.addColorsToData(res);
      this.initPieChart(this.zantingData);
    });
    this.KanbanService.getJobOrderProcessLog().subscribe((res) => {
      this.messages = res
    })
    this.intervalId = setInterval(() => {
      this.KanbanService.getJobOrderProcessLog().subscribe((res) => {
        this.messages = res
      })
    }, 5000); // 每秒执行一次
  }
  ngOnDestroy(): void {
    if (this.intervalId) {
      clearInterval(this.intervalId);
    }
  }
  initChart(): void {
    const data = [
      { value: this.processStatusData.jobOrderProcessStartedCount, name: '已开工', itemStyle: { color: '#2ac8f2' } },
      { value: this.processStatusData.jobOrderProcessNotStartedCount, name: '未开工', itemStyle: { color: '#2eead8' } },
      { value: this.processStatusData.jobOrderProcessPausedCount, name: '暂停', itemStyle: { color: '#f7b500' } },
      { value: this.processStatusData.jobOrderProcessCompletedCount, name: '已完工', itemStyle: { color: '#6ed991' } }
    ];

    const total = data.reduce((sum, item) => sum + item.value, 0);

    const option = {
      tooltip: {
        trigger: 'item',
        formatter: function (params: any) {
          return `
            <span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:${params.color};"></span>
            ${params.seriesName} <br/>
            ${params.name} : ${params.value} (${params.percent}%)
          `;
        }
      },
      legend: {
        top: '10%',
        right: '5%',
        data: data.map(item => item.name),
        textStyle: {
          color: '#fff'
        },
      },
      series: [
        {
          name: '工序状态',
          type: 'pie',
          top: "14%",
          radius: '55%',
          center: ['50%', '50%'],
          data: data,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          },
          itemStyle: {
            // 移除边框颜色和宽度
          },
          label: {
            formatter: (params) => {
              const index = data.findIndex(item => item.name === params.name);
              return `{label${index}|${params.name}\n${params.value} (${params.percent}%)}`
            },
            rich: {
              ...Object.keys(data).reduce((acc, key) => {
                const index = parseInt(key);
                acc[`label${index}`] = {
                  color: data[index].itemStyle?.color || 'defaultColor', // 动态设置颜色，提供一个默认颜色
                  fontSize: '14px', // 调整字体大小
                  lineHeight: 18 // 调整行间距
                };
                return acc;
              }, {})
            }
          }
        }
      ]
    };

    const myChart = echarts.init(document.getElementById('gongxu') as HTMLElement);
    myChart.resize(); // 初始化后立即调用 resize 方法
    window.addEventListener('resize', function () {
      myChart.resize();
    });
    myChart.setOption(option);
  }
  initChart2(): void {
    const data = [
      { value: this.reportingQualifiedRate.totalQualifiedCount, name: '合格数量', itemStyle: { color: '#4adfcb' } },
      { value: this.reportingQualifiedRate.totalUnqualifiedCount, name: '不合格数量', itemStyle: { color: '#2ac8f2' } },
      { value: this.reportingQualifiedRate.totalScrapCount, name: '报废数量', itemStyle: { color: '#f7b500' } }
    ];
    const total = this.reportingQualifiedRate.totalReportedCount;
    const option = {
      tooltip: {
        trigger: 'item',
        formatter: function (params: any) {
          if (params.name === '其他') {
            return ''; // 灰色部分不显示内容
          }
          return `
            <span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:${params.color};"></span>
            ${params.seriesName} <br/>
            ${params.name} : ${params.value} (${params.percent}%)
          `;
        }
      },
      legend: {
        top: '10%',
        right: '5%',
        data: data.map(item => ({
          name: item.name,
          itemStyle: {
            color: item.itemStyle.color // 动态设置图标颜色
          },
          textStyle: {
            color: item.itemStyle.color // 动态设置颜色
          }
        })),
      },
      series: data.map((item, index) => ({
        name: item.name,
        type: 'pie',
        top: '10%',
        radius: ['40%', '51%'], // 设置内半径和外半径，变成圆环
        center: ['20%', `${30 + index * 10}%`], // 设置不同的中心位置，增加间距
        data: [
          { value: item.value, name: item.name, itemStyle: item.itemStyle },
          { value: total - item.value, name: '其他', itemStyle: { color: '#5e6f90' } } // 灰色部分
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        label: {
          show: true, // 一直显示标签
          position: 'center',
          formatter: (params) => {
            if (params.name === '其他') {
              const percentage = ((1 - (params.value / total)) * 100).toFixed(2) + '%';
              return percentage;
            }
            const percentage = ((params.value / total) * 100).toFixed(2) + '%';
            return percentage;
          },
          textStyle: {
            fontSize: '20',
            fontWeight: 'bold',
            color: '#fff'
          }
        },
        labelLine: {
          show: false // 不显示标签连接线
        }
      })),

      media: [
        {
          query: { minAspectRatio: 1 },
          option: {
            series: data.map((item, index) => ({
              center: [`${25 + index * 25}%`, '50%']
            }))
          }
        },
        {
          option: {
            series: data.map((item, index) => ({
              center: ['50%', `${30 + index * 30}%`] // 同样增加间距
            }))
          }
        }
      ]
    };
    const myChart = echarts.init(document.getElementById('baogong') as HTMLElement);
    myChart.resize(); // 初始化后立即调用 resize 方法
    window.addEventListener('resize', function () {
      myChart.resize();
    });
    myChart.setOption(option);
  }
  ngAfterViewChecked() {
    this.scrollToBottom();
    this.cdr.detectChanges();
  }

  scrollToBottom(): void {
    const element = document.querySelector('.list');
    if (element) {
      element.scrollTop = element.scrollHeight;
    }
  }
  initBarChart(data: any): void {
    const option = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow', // 使用阴影指示器
          shadowStyle: {
            color: 'rgba(150, 150, 150, 0.3)' // 阴影颜色
          }
        }
      },
      xAxis: {
        type: 'category',
        data: data.map(item => item.mouth),
        axisLabel: {
          interval: 0, // 显示所有标签
          formatter: function (value: string) {
            return value.replace('年', '年\n'); // 在 "年" 后面换行
          },
          color: '#27bde8' // 设置字体颜色为 #27bde8
        }
      },
      yAxis: {
        type: 'value',
        axisLabel: {
          color: '#27bde8' // 设置 y 轴刻度的文本颜色为 #27bde8
        }
      },
      grid: {
        top: '15%',
        left: '2%',
        right: '2%',
        bottom: '10%',
        containLabel: true
      },
      series: [
        {
          barWidth: '30%',
          name: '工单工序数量',
          type: 'bar',
          data: data.map(item => item.jobOrderProcessMouthCount),
          itemStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [
                { offset: 0, color: 'rgba(30, 115, 225, 1)' }, // #1e73e1 不透明
                { offset: 1, color: 'rgba(28, 198, 246, 0.5)' } // #1cc6f6 半透明
              ]
            },
            borderColor: '#2adbdc', // 设置边框颜色
            borderWidth: 1 // 设置边框宽度
          },
        }
      ]
    };
    const myChart = echarts.init(document.getElementById('gongxuTask') as HTMLElement);
    myChart.setOption(option);
    window.addEventListener('resize', function () {
      myChart.resize();
    });
  }
  initLineChart(data: any): void {
    const option = {
      tooltip: {
        trigger: 'axis'
      },
      xAxis: {
        type: 'category',
        data: data.map(item => item.day),
        axisLabel: {
          color: '#27bde8' // 设置 x 轴刻度的文本颜色为 #27bde8
        }
      },
      yAxis: {
        type: 'value',
        axisLabel: {
          color: '#27bde8' // 设置 y 轴刻度的文本颜色为 #27bde8
        }
      },
      series: [
        {
          name: '完成数量',
          type: 'line',
          data: data.map(item => item.completedCount),
          itemStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [
                { offset: 0, color: 'rgba(30, 115, 225, 1)' }, // #1e73e1 不透明
                { offset: 1, color: 'rgba(28, 198, 246, 0.5)' } // #1cc6f6 半透明
              ]
            },
            borderColor: '#2adbdc', // 设置边框颜色
            borderWidth: 1 // 设置边框宽度
          },
          areaStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [
                { offset: 0, color: 'rgba(30, 115, 225, 0.5)' }, // 渐变色起点
                { offset: 1, color: 'rgba(28, 198, 246, 0.1)' } // 渐变色终点
              ]
            },
            shadowBlur: 10, // 设置阴影模糊度
            shadowColor: 'rgba(0, 0, 0, 0.5)', // 设置阴影颜色
            shadowOffsetX: 0, // 设置阴影水平偏移
            shadowOffsetY: 4 // 设置阴影垂直偏移
          },
          lineStyle: {
            width: 2 // 设置折线宽度
          },
          symbol: 'circle', // 设置折线图的标记为圆形
          symbolSize: 8 // 设置标记的大小
        }
      ]
    };
    const myChart = echarts.init(document.getElementById('wuliao') as HTMLElement);
    myChart.setOption(option);
    window.addEventListener('resize', function () {
      myChart.resize();
    });
  }
 colors = ['#0868d9', '#4caff9', '#38cafb', '#488cf7', '#4adfcb'];
 addColorsToData(data: any): any[] {
  return data.map((item, index) => ({
    ...item,
    color: this.colors[index % this.colors.length] // 按顺序循环分配颜色
  }));
}
initPieChart(data: any[]): void {
  const formattedData = data.map(item => ({
    value: item.count,
    name: item.pauseReason,
    itemStyle: { color: item.color }
  })).sort((a, b) => b.value - a.value); // 按照 value 的大小降序排列

  const rich = {};
  formattedData.forEach((item, index) => {
    rich[`label${index}`] = {
      color: item.itemStyle.color
    };
  });

  const option = {
    tooltip: {
      trigger: 'item',
      formatter: (params) => {
        // 使用 HTML 代码自定义 tooltip 内容
        return `
        <div style="display: flex; align-items: center;">
          <span style="display: inline-block; width: 10px; height: 10px; border-radius: 50%; background-color: ${params.color}; margin-right: 5px;"></span>
          ${params.seriesName} <br/>${params.name} : ${params.value} (${params.percent}%)
        </div>
      `;
      },
    },
    grid: {
      left: '0%',
      right: '5%',
      bottom: '12%',
      top: '0%',
      containLabel: true
    },
    series: [
      {
        name: '暂停原因',
        type: 'pie',
        radius: ['50%', '75%'], // 设置内外半径，形成环状
        center: ['50%', '55%'],
        label: {
          formatter: (params) => {
            const index = formattedData.findIndex(item => item.name === params.name);
            return `{label${index}|${params.percent}%}`;
          },
          rich: {
            ...rich,
            ...Object.keys(rich).reduce((acc, key) => {
              acc[key] = {
                ...rich[key],
                fontSize: '14px', // 调整字体大小
                lineHeight: 18 // 调整行间距
              };
              return acc;
            }, {})
          }
        },
        data: formattedData,
        sort: 'ascending'
      }
    ]
  };

  const chartDom = document.getElementById('zanting') as HTMLElement;
  const myChart = echarts.init(chartDom);
  myChart.setOption(option);
}
  getTotalCount(): number {
    return this.zantingData.reduce((sum, item) => sum + item.count, 0);
  }

}
